package com.flask.colorpicker.cameralibrary.util;

import ohos.aafwk.ability.DataAbilityHelper;
import ohos.app.Context;
import ohos.data.rdb.ValuesBucket;
import ohos.media.image.ImagePacker;
import ohos.media.image.PixelMap;
import ohos.media.photokit.metadata.AVStorage;
import ohos.utils.net.Uri;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * File Util
 */
public class FileUtil {
    /**
     * CacheFile Path
     */
    public static String sCacheFilePath = "";

    private final static String DST_FOLDER_NAME = "JCamera";
    private static File sParentPath;
    private static String sStoragePath = "";

    /**
     * file 初始化
     *
     * @param context Context
     */
    public static void initPath(Context context) {
        if (sParentPath == null) {
            sParentPath = getCachePathFile(context);
        }
        if ("".equals(sStoragePath)) {
            try {
                sStoragePath = sParentPath.getCanonicalPath() + File.separator + DST_FOLDER_NAME;
            } catch (IOException e) {
                LogUtil.error(LogUtil.DEFAULT_TAG, "initPath IOException:" + e.getMessage());
            }
            File file = new File(sStoragePath);
            if (!file.exists()) {
                boolean isSuccess = file.mkdir();
                if (!isSuccess) {
                    LogUtil.error(LogUtil.DEFAULT_TAG, "file create fail");
                }
            }
        }
    }

    /**
     * get Cache Path File
     *
     * @param context Context
     * @return File
     */
    public static File getCachePathFile(Context context) {
        if (context == null) {
            return null;
        }
        sCacheFilePath = context.getCacheDir().getPath();
        return context.getCacheDir();
    }

    /**
     * 存儲圖片到圖庫
     *
     * @param context context
     * @param fileName fileName
     * @param pixelMap pixelMap
     * @return 存儲圖片到圖庫
     */
    public static Uri saveImageToPicture(Context context, String fileName, PixelMap pixelMap) {
        try {
            ValuesBucket valuesBucket = new ValuesBucket();
            valuesBucket.putString(AVStorage.Images.Media.DISPLAY_NAME, fileName);
            valuesBucket.putString("relative_path", "DCIM/");
            valuesBucket.putString(AVStorage.Images.Media.MIME_TYPE, "image/JPEG");
            //应用独占
            valuesBucket.putInteger("is_pending", 1);
            DataAbilityHelper helper = DataAbilityHelper.creator(context);
            int id = helper.insert(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, valuesBucket);
            Uri uri = Uri.appendEncodedPathToUri(AVStorage.Images.Media.EXTERNAL_DATA_ABILITY_URI, String.valueOf(id));
            //这里需要"w"写权限
            FileDescriptor fd = helper.openFile(uri, "w");
            ImagePacker imagePacker = ImagePacker.create();
            ImagePacker.PackingOptions packingOptions = new ImagePacker.PackingOptions();
            OutputStream outputStream = new FileOutputStream(fd);

            packingOptions.format = "image/jpeg";
            packingOptions.quality = 90;
            boolean result = imagePacker.initializePacking(outputStream, packingOptions);
            if (result) {
                result = imagePacker.addImage(pixelMap);
                if (result) {
                    imagePacker.finalizePacking();
                }
            }
            outputStream.flush();
            outputStream.close();
            valuesBucket.clear();
            //解除独占
            valuesBucket.putInteger("is_pending", 0);
            helper.update(uri, valuesBucket, null);
            return uri;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * delete File
     *
     * @param url String
     */
    public static void deleteFile(String url) {
        File file = new File(url);
        if (file.exists()) {
           boolean ifdelete =  file.delete();
           if(ifdelete){
               System.out.println("result");
           }
        }
    }
}
